<template>
  <div class="product-management">
    <!-- 统计卡片 -->
    <lay-card>
      <div class="stats-cards">
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.total }}</div>
            <div class="stats-label">总商品数</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.published }}</div>
            <div class="stats-label">已上架</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.draft }}</div>
            <div class="stats-label">草稿</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.offline }}</div>
            <div class="stats-label">已下架</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.lowStock }}</div>
            <div class="stats-label">库存不足</div>
          </div>
        </lay-card>
      </div>
    </lay-card>

    <!-- 操作区域 -->
    <lay-card style="margin-top: 16px;">
      <div class="toolbar">
        <div class="toolbar-left">
          <lay-button type="primary" @click="handleAdd">
            <lay-icon type="layui-icon-add-1"></lay-icon>
            新增商品
          </lay-button>
          <lay-button 
            type="danger" 
            :disabled="selectedRowKeys.length === 0"
            @click="handleBatchDelete"
          >
            <lay-icon type="layui-icon-delete"></lay-icon>
            批量删除
          </lay-button>
          <lay-button @click="handleRefresh">
            <lay-icon type="layui-icon-refresh"></lay-icon>
            刷新
          </lay-button>
        </div>
        <div class="toolbar-right">
          <lay-input 
            v-model="searchForm.keyword" 
            placeholder="搜索商品名称"
            style="width: 200px;"
            @keyup.enter="handleSearch"
          >
            <template #suffix>
              <lay-icon type="layui-icon-search" @click="handleSearch"></lay-icon>
            </template>
          </lay-input>
        </div>
      </div>
    </lay-card>

    <!-- 商品表格 -->
    <lay-card style="margin-top: 15px;">
      <lay-table 
        :columns="columns" 
        :data-source="tableData"
        :loading="loading"
        v-model:selectedKeys="selectedRowKeys"
        :default-toolbar="true"
        :pagination="false"
      >
        <template #images="{ row }">
          <div class="product-images">
            <img 
              v-if="row.images && row.images.length > 0" 
              :src="row.images[0]" 
              :alt="row.name"
              class="product-image"
            />
            <span v-else class="no-image">暂无图片</span>
          </div>
        </template>
        
        <template #name="{ row }">
          <div class="product-name">
            <div class="name-text">{{ row.name }}</div>
            <div class="product-tags" v-if="row.tags && row.tags.length > 0">
              <lay-tag 
                v-for="tag in row.tags.slice(0, 3)" 
                :key="tag" 
                size="xs"
                style="margin-right: 4px;"
              >
                {{ tag }}
              </lay-tag>
            </div>
          </div>
        </template>

        <template #subtitle="{ row }">
          <div class="subtitle-text" :title="row.subtitle">
            {{ row.subtitle || '-' }}
          </div>
        </template>

        <template #category="{ row }">
          <span>{{ row.category?.name || '-' }}</span>
        </template>

        <template #brand="{ row }">
          <span>{{ row.brand?.name || '-' }}</span>
        </template>

        <template #price="{ row }">
          <div class="price-info">
            <div class="sale-price">¥{{ row.price }}</div>
            <div v-if="row.marketPrice && row.marketPrice > row.price" class="market-price">
              ¥{{ row.marketPrice }}
            </div>
          </div>
        </template>

        <template #costPrice="{ row }">
          <span class="cost-price">
            {{ row.costPrice ? `¥${row.costPrice}` : '-' }}
          </span>
        </template>

        <template #stockQuantity="{ row }">
          <span :class="getStockClass(row.stockQuantity)">
            {{ row.stockQuantity }}
          </span>
        </template>

        <template #weight="{ row }">
          <span class="weight-info">
            {{ row.weight ? `${row.weight}kg` : '-' }}
          </span>
        </template>

        <template #keywords="{ row }">
          <div class="keywords-text" :title="row.keywords">
            {{ row.keywords || '-' }}
          </div>
        </template>

        <template #status="{ row }">
          <lay-tag :type="getStatusType(row.status)" :class="getStatusClass(row.status)">
            {{ getStatusText(row.status) }}
          </lay-tag>
        </template>

        <template #badges="{ row }">
          <div class="product-badges">
            <lay-tag v-if="row.isRecommend" type="primary" size="xs" class="badge-recommend">推荐</lay-tag>
            <lay-tag v-if="row.isHot" type="danger" size="xs" class="badge-hot">热销</lay-tag>
            <lay-tag v-if="row.isNew" type="success" size="xs" class="badge-new">新品</lay-tag>
          </div>
        </template>

        <template #action="{ row }">
          <lay-button size="xs" @click="handleEdit(row)">编辑</lay-button>
          <lay-button size="xs" @click="handleViewSkus(row)">SKU</lay-button>
          <lay-dropdown>
            <lay-button size="xs">
              更多
              <lay-icon type="layui-icon-down"></lay-icon>
            </lay-button>
            <template #content>
              <lay-dropdown-menu>
                <lay-dropdown-menu-item @click="handleCopy(row)">复制</lay-dropdown-menu-item>
                <lay-dropdown-menu-item @click="handleToggleStatus(row)">
                  {{ row.status === 1 ? '下架' : '上架' }}
                </lay-dropdown-menu-item>
                <lay-dropdown-menu-item @click="handleDelete(row)" style="color: #ff5722;">
                  删除
                </lay-dropdown-menu-item>
              </lay-dropdown-menu>
            </template>
          </lay-dropdown>
        </template>
      </lay-table>

      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <lay-page 
          v-model="pagination.current"
          :total="pagination.total"
          :limit="pagination.pageSize"
          :show-count="true"
          :show-page="true"
          :show-limit="true"
          :show-skip="true"
          @change="handlePageChange"
          @limit="handlePageSizeChange"
        ></lay-page>
      </div>
    </lay-card>

    <!-- 商品弹窗 -->
    <ProductDialog 
      v-model:visible="dialogVisible"
      :product-data="currentProduct"
      :mode="dialogMode"
      @success="handleDialogSuccess"
    />

    <!-- SKU管理弹窗 -->
    <SkuDialog 
      v-model:visible="skuDialogVisible"
      :product-data="currentProduct"
      @success="handleSkuDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { layer } from '@layui/layui-vue'
import ProductDialog from './components/ProductDialog.vue'
import SkuDialog from './components/SkuDialog.vue'
import { productApi } from '../../../api/module/product'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const skuDialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit'>('add')
const currentProduct = ref<any>(null)
const selectedRowKeys = ref<string[]>([])

// 统计数据
const stats = reactive({
  total: 0,
  published: 0,
  draft: 0,
  offline: 0,
  lowStock: 0,
  outOfStock: 0
})

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref<any[]>([])

// 表格列配置
const columns = [
  {
    title: '商品图片',
    key: 'images',
    customSlot: 'images',
    width: '80px'
  },
  {
    title: '商品名称',
    key: 'name',
    customSlot: 'name',
    width: '200px'
  },
  {
    title: '副标题',
    key: 'subtitle',
    customSlot: 'subtitle',
    width: '150px'
  },
  {
    title: 'SPU编码',
    key: 'spuCode',
    width: '120px'
  },
  {
    title: '分类',
    key: 'category',
    customSlot: 'category',
    width: '100px'
  },
  {
    title: '品牌',
    key: 'brand',
    customSlot: 'brand',
    width: '100px'
  },
  {
    title: '价格',
    key: 'price',
    customSlot: 'price',
    width: '120px'
  },
  {
    title: '成本价',
    key: 'costPrice',
    customSlot: 'costPrice',
    width: '100px'
  },
  {
    title: '库存',
    key: 'stockQuantity',
    customSlot: 'stockQuantity',
    width: '80px'
  },
  {
    title: '销量',
    key: 'saleCount',
    width: '80px'
  },
  {
    title: '重量(kg)',
    key: 'weight',
    customSlot: 'weight',
    width: '100px'
  },
  {
    title: '关键词',
    key: 'keywords',
    customSlot: 'keywords',
    width: '150px'
  },
  {
    title: '状态',
    key: 'status',
    customSlot: 'status',
    width: '80px'
  },
  {
    title: '标签',
    key: 'badges',
    customSlot: 'badges',
    width: '120px'
  },
  {
    title: '排序',
    key: 'sortOrder',
    width: '80px'
  },
  {
    title: '创建时间',
    key: 'createdAt',
    width: '150px'
  },
  {
    title: '操作',
    key: 'action',
    customSlot: 'action',
    width: '150px',
    fixed: 'right'
  }
]

// 获取库存样式类
const getStockClass = (stock: number) => {
  if (stock === 0) return 'stock-empty'
  if (stock < 10) return 'stock-low'
  return 'stock-normal'
}

// 获取状态类型
const getStatusType = (status: number) => {
  switch (status) {
    case 1: return 'success'
    case 0: return 'danger'
    case 2: return 'warning'
    default: return 'default'
  }
}

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 1: return '已上架'
    case 0: return '已下架'
    case 2: return '草稿'
    default: return '未知'
  }
}

// 获取状态CSS类
const getStatusClass = (status: number) => {
  switch (status) {
    case 1: return 'status-online'
    case 0: return 'status-offline'
    case 2: return 'status-draft'
    default: return 'status-unknown'
  }
}

// 获取商品列表
const getProductList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    const response = await productApi.getProductList(params)
    if (response.code === 200) {
      tableData.value = response.data.list
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    layer.msg('获取商品列表失败', { icon: 2 })
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const getStats = async () => {
  try {
    const response = await productApi.getProductStats()
    if (response.code === 200) {
      const data = response.data
      // 映射后端字段到前端字段
      Object.assign(stats, {
        total: data.totalProducts || 0,
        published: data.onShelfProducts || 0,
        draft: data.preOrderProducts || 0,
        offline: data.offShelfProducts || 0,
        lowStock: 0, // 后端暂无此字段
        outOfStock: 0 // 后端暂无此字段
      })
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}



// 搜索
const handleSearch = () => {
  pagination.current = 1
  getProductList()
}

// 刷新
const handleRefresh = () => {
  Object.assign(searchForm, {
    keyword: ''
  })
  pagination.current = 1
  getProductList()
  getStats()
}

// 新增商品
const handleAdd = () => {
  currentProduct.value = null
  dialogMode.value = 'add'
  dialogVisible.value = true
}

// 编辑商品
const handleEdit = (row: any) => {
  currentProduct.value = { ...row }
  dialogMode.value = 'edit'
  dialogVisible.value = true
}

// 复制商品
const handleCopy = (row: any) => {
  const copyData = { ...row }
  delete copyData.id
  copyData.name = `${copyData.name} - 副本`
  currentProduct.value = copyData
  dialogMode.value = 'add'
  dialogVisible.value = true
}

// 查看SKU
const handleViewSkus = (row: any) => {
  currentProduct.value = { ...row }
  skuDialogVisible.value = true
}

// 切换状态
const handleToggleStatus = async (row: any) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1
    await productApi.updateProductStatus(row.id, newStatus)
    layer.msg('状态更新成功', { icon: 1 })
    getProductList()
    getStats()
  } catch (error) {
    console.error('更新状态失败:', error)
    layer.msg('更新状态失败', { icon: 2 })
  }
}

// 删除商品
const handleDelete = (row: any) => {
  layer.confirm(`确定要删除商品"${row.name}"吗？`, {
    title: '确认删除',
    icon: 3
  }, async () => {
    try {
      await productApi.deleteProduct(row.id)
      layer.msg('删除成功', { icon: 1 })
      getProductList()
      getStats()
    } catch (error) {
      console.error('删除失败:', error)
      layer.msg('删除失败', { icon: 2 })
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    layer.msg('请选择要删除的商品', { icon: 3 })
    return
  }

  layer.confirm(`确定要删除选中的 ${selectedRowKeys.value.length} 个商品吗？`, {
    title: '确认批量删除',
    icon: 3
  }, async () => {
    try {
      await productApi.batchDeleteProducts(selectedRowKeys.value)
      layer.msg('批量删除成功', { icon: 1 })
      selectedRowKeys.value = []
      getProductList()
      getStats()
    } catch (error) {
      console.error('批量删除失败:', error)
      layer.msg('批量删除失败', { icon: 2 })
    }
  })
}



// 分页变化
const handlePageChange = (page: number) => {
  pagination.current = page
  getProductList()
}

// 每页数量变化
const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  getProductList()
}

// 弹窗成功回调
const handleDialogSuccess = () => {
  getProductList()
  getStats()
}

// SKU弹窗成功回调
const handleSkuDialogSuccess = () => {
  getProductList()
}

// 初始化
onMounted(() => {
  getProductList()
  getStats()
})
</script>

<style scoped>
.product-management {
  padding: 0;
}

.stats-cards {
  display: flex;
  gap: 16px;
}

.stats-card {
  flex: 1;
  min-width: 0;
}

.stats-content {
  text-align: center;
  padding: 20px;
}

.stats-number {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #666;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.toolbar-left {
  display: flex;
  gap: 8px;
}

.toolbar-right {
  display: flex;
  align-items: center;
}

.product-images {
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
}

.no-image {
  color: #999;
  font-size: 12px;
}

.product-name {
  max-width: 180px;
}

.name-text {
  font-weight: 500;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 2px;
}

.price-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.sale-price {
  font-weight: 600;
  color: #ff5722;
  font-size: 14px;
}

.market-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

.cost-price {
  color: #666;
  font-size: 13px;
}

.weight-info {
  color: #666;
  font-size: 13px;
}

.subtitle-text,
.keywords-text {
  max-width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #666;
  font-size: 12px;
}

.stock-normal {
  color: #52c41a;
}

.stock-low {
  color: #faad14;
}

.stock-empty {
  color: #ff4d4f;
}

.product-badges {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
}

.badge-recommend {
  background-color: #1890ff !important;
  color: white !important;
  border: 1px solid #1890ff !important;
}

.badge-hot {
  background-color: #ff4d4f !important;
  color: white !important;
  border: 1px solid #ff4d4f !important;
}

.badge-new {
  background-color: #52c41a !important;
  color: white !important;
  border: 1px solid #52c41a !important;
}

.status-online {
  background-color: #52c41a !important;
  color: white !important;
  border: 1px solid #52c41a !important;
}

.status-offline {
  background-color: #ff4d4f !important;
  color: white !important;
  border: 1px solid #ff4d4f !important;
}

.status-draft {
  background-color: #faad14 !important;
  color: white !important;
  border: 1px solid #faad14 !important;
}

.status-unknown {
  background-color: #d9d9d9 !important;
  color: #666 !important;
  border: 1px solid #d9d9d9 !important;
}

.pagination-wrapper {
  margin-top: 16px;
  text-align: right;
}
</style>